package com.example.mybatisplusdemo.controller;

import com.example.mybatisplusdemo.common.BaseContext;
import com.example.mybatisplusdemo.dto.UserLoginDTO;
import com.example.mybatisplusdemo.dto.UserPageDTO;
import com.example.mybatisplusdemo.entity.User;
import com.example.mybatisplusdemo.mapper.UserMapper;
import com.example.mybatisplusdemo.result.PageResult;
import com.example.mybatisplusdemo.result.Result;
import com.example.mybatisplusdemo.service.UserService;
import com.example.mybatisplusdemo.util.JwtUtil;
import com.example.mybatisplusdemo.vo.UserLoginVO;
import com.example.mybatisplusdemo.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@Slf4j
@Tag(name = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserService userService;
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expire-time}")
    private Long expireTime;


    /**
     * 根据ID查询用户信息
     * @return 用户信息
     */
    @Operation(summary = "根据ID查询用户信息")
    @GetMapping("/getUserById")
    public ResponseEntity<UserVO> getUserById() {
        Long userId = BaseContext.getCurrentId();
        log.info("当前用户ID：{}", userId);
        UserVO userVO = userMapper.selectUserById(userId);
        if (userVO == null) {
            // 可以选择返回一个默认的UserVO或者抛出自定义异常
            return new ResponseEntity<>(new UserVO(), HttpStatus.NOT_FOUND);
        }
        // 进一步的数据有效性验证可以根据具体业务需求添加
        return new ResponseEntity<>(userVO, HttpStatus.OK);
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@Valid @RequestBody UserLoginDTO userLoginDTO){
        User user = userService.login(userLoginDTO);

        //下发token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(secret, expireTime, claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .age(user.getAge())
                .name(user.getName())
                .email(user.getEmail())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    /**
     * 分页查询
     * @param userPageDTO 查询参数
     */
    @Operation(summary = "分页查询")
    @GetMapping("/page")
    public Result<PageResult<User>> getPage(UserPageDTO userPageDTO){
        PageResult<User> pageResult = userService.getPage(userPageDTO);

        return Result.success(pageResult);
    }

}
